//
//  EPBottomView.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-1-23.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EPBottomView.h"
#import "UIView+Addtions.h"
#import "EpointConsts.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>
#import <MediaPlayer/MediaPlayer.h>
#import "PGPopoverView.h"

#import "EpointMailSendViewController.h"
#import "EpointAttachViewController.h"
#import "AttachTableViewCell.h"

#import "EPAttachView.h"
#import "NSString+Addtions.h"

#import "QBImagePickerController.h"
#import "ShowImageViewController.h"
#import "EpointAttachOpenViewController.h"
#import "EpointAttachDownloadListViewController.h"

#define TopViewCellHeight 48

#define InfoType_Image @"public.image"
#define InfoType_Movie @"public.movie"

@interface EPBottomView () <UIScrollViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, EPAttachViewDelegate, PGPopoverViewDelegate, PGPopoverViewDataSource, QBImagePickerControllerDelegate> {
    BOOL isMoving;
    
    NSURL *sourceURL;
    NSString *resultQuality;
    
    int imageCount;
    int videlCount;
    
    NSString *preName;
    
    int selectedIndex;
    
    UIInterfaceOrientation currentOrient;
    
    NSMutableArray *selectPhotoArray;
    NSMutableArray *selectVideoArray;
    NSMutableArray *cachePhotoArray;//图片缓存
}

@property (nonatomic, strong) EPAttachView *attachView;
@property (nonatomic, strong) UIPopoverController *popoverController;
@property (nonatomic, strong) NSMutableArray *sandboxAttachArray;
@property (nonatomic, strong) NSMutableArray *selectedSandboxIndexs;

@end

@implementation EPBottomView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (id)init {
    self = [super initWithFrame:CGRectMake(0, 0, AppWidth, BottomViewHeight)];//AppHeight-SystemTakeHeight
    cachePhotoArray =[[NSMutableArray alloc] init];
    self.backgroundColor = COLOR(231, 234, 239);
    if (self) {
        [self addSubViews];
    }
    return self;
}

- (void)dealloc {
    if (CurrentDeviceISiPad) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
}

- (void)addSubViews {

    if (CurrentDeviceISiPad) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];
    }
    
    [self addSeparatorLines];
    [self addTopButtonsView];
    [self addAttachView];
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"MMdd_"];
    preName = [formatter stringFromDate:[NSDate date]];

    selectedIndex = -1;
}

- (void)deviceOrientationChange {
    
    if (_popoverController.popoverVisible == NO) {
        return;
    }
    
    UIInterfaceOrientation tempOrient= [UIApplication sharedApplication].statusBarOrientation;
    if (currentOrient != tempOrient) {
        currentOrient = tempOrient;
    } else {
        return;
    }
    
    UIImagePickerController *picker = (UIImagePickerController *)_popoverController.contentViewController;
    
    CGAffineTransform transform = picker.cameraViewTransform;
    if (tempOrient == UIInterfaceOrientationLandscapeRight) {
        transform = CGAffineTransformRotate(transform, M_PI);
    } else if(tempOrient == UIInterfaceOrientationLandscapeLeft) {
        transform = CGAffineTransformRotate(transform, -M_PI);
    }
    
    picker.cameraViewTransform = transform;
}

- (void)getImageSize:(UIImage *)image {

    int  perMBBytes = 1024*1024;
    
    CGImageRef cgimage = image.CGImage;
    size_t bpp = CGImageGetBitsPerPixel(cgimage);
    size_t bpc = CGImageGetBitsPerComponent(cgimage);
    size_t bytes_per_pixel = bpp / bpc;
    
    long lPixelsPerMB  = perMBBytes/bytes_per_pixel;
    
    
    long totalPixel = CGImageGetWidth(image.CGImage)*CGImageGetHeight(image.CGImage);
    
    
    long totalFileMB = totalPixel/lPixelsPerMB;
    NSLog(@"%ld", totalFileMB);
}

- (void)addSeparatorLines {

    UIImageView *separatorLine1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, AppWidth*2, 1)];
    separatorLine1.alpha = 0.5;
    separatorLine1.backgroundColor = [UIColor grayColor];
    [self addSubview:separatorLine1];
    
    UIImageView *separatorLine2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, TopViewCellHeight, AppWidth*2, 1)];
    separatorLine2.alpha = 0.5;
    separatorLine2.backgroundColor = [UIColor grayColor];
    [self addSubview:separatorLine2];
    
    UIImageView *separatorLine3 = [[UIImageView alloc] initWithFrame:CGRectMake(0, TopViewCellHeight+1, AppWidth*2, 1)];
    separatorLine3.alpha = 0.5;
    separatorLine3.backgroundColor = COLOR(255, 255, 255);
    [self addSubview:separatorLine3];
}

- (void)addTopButtonsView {
    
    UIButton *cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cameraBtn setBackgroundImage:[UIImage imageNamed:@"icon_attach_toolbar_camera"] forState:UIControlStateNormal];
    cameraBtn.frame = CGRectMake(0, 0, 32, 24);
    [cameraBtn addTarget:self action:@selector(cameraBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cameraBtn];
    
    UIButton *photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [photoBtn setBackgroundImage:[UIImage imageNamed:@"icon_attach_toolbar_album"] forState:UIControlStateNormal];
    photoBtn.frame = CGRectMake(0, 0, 32, 24);
    [photoBtn addTarget:self action:@selector(photoBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:photoBtn];
    
    UIButton *videoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [videoBtn setBackgroundImage:[UIImage imageNamed:@"icon_attach_toolbar_video"] forState:UIControlStateNormal];
    videoBtn.frame = CGRectMake(0, 0, 32, 24);
    [videoBtn addTarget:self action:@selector(videoBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:videoBtn];
    
    UIButton *fileBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [fileBtn setBackgroundImage:[UIImage imageNamed:@"icon_attach_toolbar_ftn"] forState:UIControlStateNormal];
    fileBtn.frame = CGRectMake(0, 0, 32, 24);
    [fileBtn addTarget:self action:@selector(fileBtnPressed) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:fileBtn];
    
    CGFloat itemPadding = (AppWidth - 4*32)/5;
    CGFloat top = (TopViewCellHeight - 24)*0.5;
    
    cameraBtn.left = itemPadding;
    cameraBtn.top = top;
    
    photoBtn.left = itemPadding*2 + 32;
    photoBtn.top = top;
    
    videoBtn.left = itemPadding*3 + 32*2;
    videoBtn.top = top;
    
    fileBtn.left = itemPadding*4 + 32*3;
    fileBtn.top = top;
}

- (void)addAttachView {
    
    self.attachArray = [[NSMutableArray alloc] init];
    
    self.attachView = [[EPAttachView alloc] initWithFrame:CGRectMake(0, TopViewCellHeight, AppWidth, BottomViewHeight-TopViewCellHeight)];
    _attachView.delegate = self;
    [self addSubview:_attachView];

    [self initSandboxAttach];
}

- (void)initSandboxAttach { 
    self.sandboxAttachArray = [EpointAttachViewController getAllAttachArray];
    self.selectedSandboxIndexs = [[NSMutableArray alloc] initWithCapacity:_sandboxAttachArray.count];
}

#pragma mark - button action

- (void)cameraBtnPressed:(UIButton *)button {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = sourceType;
    
    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    picker.mediaTypes = availableMedia;
    
    if (CurrentDeviceISiPad) {
        UIInterfaceOrientation tempOrient= [UIApplication sharedApplication].statusBarOrientation;
        currentOrient = tempOrient;
        CGAffineTransform transform = picker.cameraViewTransform;
        if (tempOrient == UIInterfaceOrientationLandscapeRight) {
            transform = CGAffineTransformRotate(transform, -M_PI*0.5);
        } else if(tempOrient == UIInterfaceOrientationLandscapeLeft) {
            transform = CGAffineTransformRotate(transform, M_PI*0.5);
        }
        picker.cameraViewTransform = transform;
        UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:picker];
        [popover setPopoverContentSize:CGSizeMake(1000, 1000) animated:YES];
        self.popoverController = popover;
        [_popoverController presentPopoverFromRect:button.frame inView:self permittedArrowDirections:UIPopoverArrowDirectionAny animated:NO];//CGRectMake(0, 0, 300, 300)
    } else {
        [_parentCtrl presentViewController:picker animated:YES completion:nil];
    }
}

- (void)photoBtnPressed:(UIButton *)button {
//    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//    picker.delegate = self;
//    picker.allowsEditing = NO;
//    picker.sourceType = sourceType;
//    
//    if (CurrentDeviceISiPad) {
//        UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:picker];
//        self.popoverController = popover;
//        [_popoverController presentPopoverFromRect:button.frame inView:self permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
//    } else {
//        [_parentCtrl presentViewController:picker animated:YES completion:nil];
//    }
    
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.selectDicArray = selectPhotoArray;
    //    imagePickerController.filterType = QBImagePickerFilterTypeAllVideos;
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [_parentCtrl presentViewController:navigationController animated:YES completion:NULL];
    
}

- (void)videoBtnPressed:(UIButton *)button {
//    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//    picker.delegate = self;
//    picker.allowsEditing = NO;
//    picker.sourceType = sourceType;
//    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
//    picker.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];
//
//    if (CurrentDeviceISiPad) {
//        UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:picker];
//        self.popoverController = popover;
//        [_popoverController presentPopoverFromRect:button.frame inView:self permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
//    } else {
//        [_parentCtrl presentViewController:picker animated:YES completion:nil];
//    }
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.selectDicArray = selectVideoArray;
    imagePickerController.filterType = QBImagePickerFilterTypeAllVideos;
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [_parentCtrl presentViewController:navigationController animated:YES completion:NULL];
}

- (void)fileBtnPressed {
    NSLog(@"fileBtnPressed ...");
//    CGFloat width = AppWidth - 60;
//    CGFloat height = PGPopTitleHeight + 44*5;
//    PGPopoverView *popoverView = [[PGPopoverView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
//    popoverView.parentView = _parentCtrl.view;
//    popoverView.delegate = self;
//    popoverView.datasource = self;
//    popoverView.selectedIndexArray = _selectedSandboxIndexs;
//    [popoverView setTitle:@"附件"];
//    [popoverView show];
    if (_delegate && [_delegate respondsToSelector:@selector(shouldShowFileMutableSelectCtrl:)]) {
        [_delegate shouldShowFileMutableSelectCtrl:_selectedSandboxIndexs];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (CurrentDeviceISiPad) {
        [_popoverController dismissPopoverAnimated:YES];
    } else {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }

    UIImage *image;

    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        if ([[picker.mediaTypes lastObject] isEqualToString:@"public.image"]) {
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
            NSArray *array = @[image, @"0"];
            [self performSelector:@selector(saveImage:) withObject:array afterDelay:0.5];
        } else {
            NSMutableDictionary *infoDic = [NSMutableDictionary dictionaryWithDictionary:info];
            [infoDic setValue:@"0" forKey:@"isCamera"];
            [self saveVideo:infoDic];
        }
    } else {
        NSLog(@"type:%@", picker.mediaTypes);
        if ([[picker.mediaTypes lastObject] isEqualToString:@"public.image"]) {
            image = [info objectForKey:UIImagePickerControllerEditedImage];
            [self performSelector:@selector(saveImage:) withObject:@[] afterDelay:0.5];
        } else {
            NSString *infoType = [info objectForKey:UIImagePickerControllerMediaType];
            if ([infoType isEqualToString:InfoType_Image]) {
                image = [info objectForKey:UIImagePickerControllerOriginalImage];
                NSArray *array = @[image, @"1"];
                [self performSelector:@selector(saveImage:) withObject:array afterDelay:0.0];
            } else if ([infoType isEqualToString:InfoType_Movie]) {
                NSMutableDictionary *infoDic = [NSMutableDictionary dictionaryWithDictionary:info];
                [infoDic setValue:@"1" forKey:@"isCamera"];
                [self saveVideo:infoDic];
            }
        }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if (CurrentDeviceISiPad) {
        [_popoverController dismissPopoverAnimated:YES];
    } else {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - deal with image, videl

- (void)saveVideo:(NSDictionary *)info {
    
    NSURL *videoURL = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
    
//    NSLog(@"length:%@", [NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
//    NSLog(@"size:%@", [NSString stringWithFormat:@"%f kb", [self getFileSize:[[videoURL absoluteString] substringFromIndex:16]]]);
    NSLog(@"%@" ,[[videoURL absoluteString] substringFromIndex:16]);
    
    resultQuality = AVAssetExportPresetMediumQuality;
    [self compressedFileSize:info];
}

- (void)compressedFileSize:(NSDictionary *)info {

    NSURL *videoURL = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
    if (videoURL==nil || [videoURL absoluteString].length == 0) {
        videoURL = [info objectForKey:@"UIImagePickerControllerMediaURL"];
    }
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    if ([compatiblePresets containsObject:resultQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:resultQuality];
        
        videlCount++;
        NSString *videoName = [NSString stringWithFormat:@"%@%d.mp4", preName, videlCount];
        
        NSString *resultPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/temp/%@", videoName];
        NSString *fileGroup = [NSHomeDirectory() stringByAppendingString:@"/Documents/temp"];
        if (![self isExistsFile:fileGroup]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:fileGroup withIntermediateDirectories:YES attributes:nil error:nil];
        }

        if ([self isExistsFile:resultPath]) {
            NSDictionary* dictFile = [[NSFileManager defaultManager] attributesOfItemAtPath:resultPath error:nil];
            long nFileSize = [dictFile fileSize];
            NSLog(@"\n\nnFileSize :%ld", nFileSize);
            [[NSFileManager defaultManager] removeItemAtPath:resultPath error:nil];
        }
        
        NSLog(@"%@", resultPath);
        exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
        exportSession.outputFileType = AVFileTypeMPEG4;
        [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
         {
             switch (exportSession.status) {
                 case AVAssetExportSessionStatusUnknown:
                     NSLog(@"AVAssetExportSessionStatusUnknown");
                     break;
                 case AVAssetExportSessionStatusWaiting:
                     NSLog(@"AVAssetExportSessionStatusWaiting");
                     break;
                 case AVAssetExportSessionStatusExporting:
                     NSLog(@"AVAssetExportSessionStatusExporting");
                     break;
                 case AVAssetExportSessionStatusCompleted: {
                     NSLog(@"AVAssetExportSessionStatusCompleted");
                     NSLog(@"Completed:%@", exportSession.outputURL);
                     [self addVideoFile:exportSession.outputURL withInfo:info];
                 }
                     break;
                 case AVAssetExportSessionStatusFailed:
                     //fail;
                     NSLog(@"AVAssetExportSessionStatusFailed");
                     break;
             }
         }];
    }
}

- (CGFloat) getFileSize:(NSString *)path {
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size;//  /1024
    }
    return filesize;
}

- (CGFloat)getVideoLength:(NSURL *)URL {
    NSDictionary *opts =
    [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:URL options:opts];
    float second = 0;
    second = urlAsset.duration.value/urlAsset.duration.timescale;
    return second;
}

- (void)saveImage:(NSArray *)array {

    UIImage *image = [array objectAtIndex:0];
    imageCount++;
    //NSData *data = UIImagePNGRepresentation(image);
    NSData *data = UIImageJPEGRepresentation(image, RepresentationValue);
    NSString *imageName = [NSString stringWithFormat:@"%@%d.jpg", preName, imageCount];

    NSDictionary *imageDic = @{@"type": [[NSNumber alloc] initWithInt:PHOTO_TYPE],
                               @"title": imageName,
                               @"isCamera": [array objectAtIndex:1],
                               @"image": image,
                               @"size": [self addUnitForSize:data.length withDecimal:2]
                               };//@"size": data
    NSMutableDictionary *imageMutableDic = [[NSMutableDictionary alloc] initWithDictionary:imageDic];
    if ([[array objectAtIndex:1] isEqualToString:@"0"]) {
        if ([array objectAtIndex:2]) {
            [imageMutableDic setObject:[[array objectAtIndex:2] absoluteString] forKey:@"fileUrl"];
        }
        if ([array objectAtIndex:3]) {
            [imageMutableDic setObject:[array objectAtIndex:3] forKey:@"selectDic"];
        }
    }
    
    [_attachArray addObject:imageMutableDic];
    [_attachView reloadItemData];
    [_parentCtrl attachNumberChanged:_attachArray.count];
}

- (void)addVideoFile:(NSURL *)videoFile withInfo:(NSDictionary *)info {
    
    float size;
    
    if (ISIOS7) {
        size = [self getFileSize:[[videoFile absoluteString] substringFromIndex:7]];
    } else {
        size = [self getFileSize:[[videoFile absoluteString] substringFromIndex:16]];
    }
    NSString *fileSize = [self addUnitForSize:size withDecimal:2];
    NSString *fileName = [videoFile lastPathComponent];  //@"videoBG.png"
    
    NSURL *fileUrl = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
    if (fileUrl==nil || [fileUrl absoluteString].length == 0) {
        fileUrl = [info objectForKey:@"UIImagePickerControllerMediaURL"];
    }
    
    UIImage *image;

    if ([[info objectForKey:@"isCamera"] boolValue]) {
        image = [UIImage imageNamed:@"videoBG.png"];
    } else {
        image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    }

    NSDictionary *videoDic = @{@"type": [[NSNumber alloc] initWithInt:VIDEO_TYPE],
                               @"title": fileName,
                               @"image": image,
                               @"isCamera": [info objectForKey:@"isCamera"],
                               @"size": fileSize,
                               @"videoUrl": videoFile,
                               @"fileUrl": [fileUrl absoluteString]};
    NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:videoDic];
    if ([info objectForKey:@"selectDic"]) {
        [mutableDic setObject:[info objectForKey:@"selectDic"] forKey:@"selectDic"];
    }
    [_attachArray addObject:mutableDic];
    NSLog(@"0000");
    [_attachView reloadItemData];
    [_parentCtrl attachNumberChanged:_attachArray.count];
}

#pragma mark - show and hide animations

- (void)showOrHideBottomView:(NSArray *)array {
    
    if (isMoving) {
        return;
    }
    
    _isShow = !_isShow;
    isMoving = YES;
    [UIView beginAnimations:@"move" context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animatedStop:)];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    CGFloat top;
    CGFloat buttonTop;
    CGFloat changeValue;
    if (_isShow) {
        top = AppHeight-BottomViewHeight-SystemTakeHeight;
        buttonTop = AppHeight-SystemTakeHeight-25-5-BottomViewHeight;
        changeValue = -BottomViewHeight;
    } else {
        top = AppHeight-SystemTakeHeight;
        buttonTop = AppHeight-SystemTakeHeight-25-5;
        changeValue = BottomViewHeight;
    }
    
    UIButton *attachButton = [array objectAtIndex:0];
    attachButton.top = buttonTop;
    
    UIButton *keyboardBtn = [array objectAtIndex:1];
    keyboardBtn.top = buttonTop+2;
    
    UIView *msgNoticeView = [array objectAtIndex:2];
    msgNoticeView.top = buttonTop+1;
    
    self.top = top;
    [UIView commitAnimations];
}

- (void)animatedStop:(id)sender {
    isMoving = NO;
}

#pragma mark - UISheetActionDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (selectedIndex == -1) {
        return;
    }
    if (buttonIndex == 0) {
        NSLog(@"Delete ...%d", buttonIndex);
        
        NSDictionary *attachDic = [_attachArray objectAtIndex:selectedIndex];
        AttachType attachType = [[attachDic objectForKey:@"type"] intValue];
        switch (attachType) {
            case FILE_TYPE:
                [self removeSandboxItem:selectedIndex];
                break;
            case PHOTO_TYPE: {
                if ([[attachDic objectForKey:@"isCamera"] isEqualToString:@"0"]) {
                    [self removeSelectPhoto:selectedIndex];
                }
            }
                break;
            case VIDEO_TYPE: {
                if ([[attachDic objectForKey:@"isCamera"] isEqualToString:@"0"]) {
                    [self removeSelectVideo:selectedIndex];
                }
            }
                break;
            default:
                break;
        }
        [_attachArray removeObjectAtIndex:selectedIndex];
        [_attachView reloadItemData];
        [_parentCtrl attachNumberChanged:_attachArray.count];
    } else {
        NSLog(@"Open ...%d", buttonIndex);
        if (_delegate && [_delegate respondsToSelector:@selector(openAttach)]) {
            [_delegate openAttach];
        }
        
        NSDictionary *dic = [_attachArray objectAtIndex:selectedIndex];
        
        AttachType attachType = [[dic objectForKey:@"type"] intValue];
        
        if (attachType == VIDEO_TYPE) {

            NSURL *url = [dic objectForKey:@"videoUrl"];
//            MPMoviePlayerController *rootPlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
//            //    self.rootPlayer.scalingMode = MPMovieScalingModeAspectFill;
//            rootPlayer.view.frame = CGRectMake(10, 10, 300, 440);
//            rootPlayer.movieSourceType=MPMovieSourceTypeFile;
//            [rootPlayer prepareToPlay];
//
//            [_parentCtrl.view addSubview:rootPlayer.view];
//            [rootPlayer play];
            
            MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
            [self.parentCtrl presentMoviePlayerViewControllerAnimated:playerVC];
            [playerVC.moviePlayer play];
            
        } else if (attachType == PHOTO_TYPE) {
            
            NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:2];
            [params setObject:[dic objectForKey:@"title"] forKey:@"title"];
            [params setObject:[dic objectForKey:@"image"] forKey:@"image"];
            ShowImageViewController *imageCtrl = [[ShowImageViewController alloc] init];
            imageCtrl.passParam = params;
            [self.parentCtrl.navigationController pushViewController:imageCtrl animated:YES];
        } else {
            NSLog(@"dic:%@", dic);
            NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
            [params setObject:[dic objectForKey:@"title"] forKey:@"title"];
            NSString *folderGuid = [[[dic objectForKey:@"fileUrl"] stringByDeletingLastPathComponent] lastPathComponent];
            [params setObject:folderGuid forKey:@"folderguid"];
            EpointAttachOpenViewController *ao = [[EpointAttachOpenViewController alloc]init];
            ao.passParam = params;
            [_parentCtrl.navigationController pushViewController:ao animated:YES];
        }
    }
    selectedIndex = -1;
}

#pragma mark - EPAttachViewDelegate

- (void)epattachView:(EPAttachView *)epacttachView didSelected:(int)index {
    NSLog(@"didSelected:%d", index);
    selectedIndex = index;
    NSDictionary *dic = [_attachArray objectAtIndex:index];
    NSString *title = [dic objectForKey:@"title"];
    AttachType attachType = [[dic objectForKey:@"type"] intValue];
    
    UIActionSheet *sheet;
    if (attachType == UNRECOG_TYPE) {
        sheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:nil];
    } else {
        sheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:@"查看", nil];
    }
    [sheet setActionSheetStyle:UIActionSheetStyleBlackOpaque];
    [sheet showInView:[self window]];
}

- (NSInteger)numberOfItemInepattachView:(EPAttachView *)epacttachView {
    return _attachArray.count;
}
- (EPAttachItem *)epattachView:(EPAttachView *)epacttachView itemAtIndex:(int)index {
    EPAttachItem *item = [[EPAttachItem alloc] initWithDefaultStyle];
    
    NSDictionary *itemDic = [_attachArray objectAtIndex:index];
    AttachType attachType = [[itemDic objectForKey:@"type"] intValue];

    switch (attachType) {
        case PHOTO_TYPE:
            item.itemImage = [itemDic objectForKey:@"image"];
            break;
        case FILE_TYPE:
            item.itemImage = [UIImage imageNamed:[itemDic objectForKey:@"image"]];
            break;
        case VIDEO_TYPE:
            item.itemImage = [itemDic objectForKey:@"image"];//[UIImage imageNamed:[itemDic objectForKey:@"image"]];
            break;
        case UNRECOG_TYPE: {
            //item.itemImage = [itemDic objectForKey:@"image"];//[UIImage imageNamed:[itemDic objectForKey:@"image"]];
            NSString *fileName = [itemDic objectForKey:@"title"];
            item.itemImage = [UIImage imageNamed:[EpointAttachDownloadListViewController getImageNameByFileName:fileName]];
        }
            break;
        default:
            break;
    }

    item.titleLabel.text = [itemDic objectForKey:@"title"];
    item.sizeLabel.text = [itemDic objectForKey:@"size"];
    return item;
}

#pragma mark - some deal funciton

- (NSString *)addUnitForSize:(NSInteger)fileSize withDecimal:(int)number {
    int multipleValue = pow(10, number);
    double sizeD;
    NSString *unit = @"B";
    if (fileSize < 1000) {
        return [NSString stringWithFormat:@"%d%@", fileSize, unit];
    } else if (fileSize >= 1000 && fileSize < 1000000) {
        unit = @"K";
        sizeD = fileSize/1000.0;
    } else {
        unit = @"M";
        sizeD = fileSize/1000000.0;
    }
    double result = round(sizeD*multipleValue)/multipleValue;
    
    switch (number) {
        case 1:
            return [NSString stringWithFormat:@"%0.1f%@", result, unit];
            break;
        case 2:
            return [NSString stringWithFormat:@"%0.2f%@", result, unit];
            break;
        default:
            return [NSString stringWithFormat:@"%0.0f%@", result, unit];
            break;
    }
}

- (BOOL)isExistsFile:(NSString *)filePath {
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}

#pragma mark - PGPopoverViewDataSource

- (UITableViewCell *)popoverView:(PGPopoverView *)popoverView
                cellForIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    AttachTableViewCell *cell = [[AttachTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    cell.attachInfo = [_sandboxAttachArray objectAtIndex:indexPath.row];
    return cell;
}

- (NSInteger)popoverView:(PGPopoverView *)popoverView
   numberOfRowsInSection:(NSInteger)section {
    return _sandboxAttachArray.count;
}

#pragma mark - PGPopoverViewDelegate

- (void)popoverViewCancel:(PGPopoverView *)popoverView {
    NSLog(@"Cancel ...");
}

- (CGFloat)popoverView:(PGPopoverView *)popoverView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0;
}

- (void)dismissFromParentView:(PGPopoverView *)popoverView {
    NSLog(@"dismiss ...");
}

- (void)okButtonPressed:(NSMutableArray *)mutableArray {
    NSLog(@"mutableArray:%@", mutableArray);
    self.selectedSandboxIndexs = mutableArray;
    
    NSMutableArray *shouldDeleteArray = [[NSMutableArray alloc] initWithCapacity:_attachArray.count];

    for (NSDictionary *attachDic in _attachArray) {
        AttachType attachType = [[attachDic objectForKey:@"type"] intValue];
        if (attachType != FILE_TYPE) {
            continue;
        }
        
        NSString *filePath = [attachDic objectForKey:@"fileUrl"];

        BOOL isFound = NO;

        for (NSString *selectIndex in mutableArray) {
            AttachInfo *info = [_sandboxAttachArray objectAtIndex:[selectIndex intValue]];
            if ([info.filePath isEqualToString:filePath]) {
                isFound = YES;
                break;
            }
        }
        
        if (isFound == NO) {
            [shouldDeleteArray addObject:attachDic];
        }
    }
    
    [_attachArray removeObjectsInArray:shouldDeleteArray];

    NSMutableArray *shouldAddArray = [[NSMutableArray alloc] initWithCapacity:mutableArray.count];
    
    for (NSString *selectIndex in mutableArray) {
        AttachInfo *info = [_sandboxAttachArray objectAtIndex:[selectIndex intValue]];
        
        BOOL isFound = NO;
        for (NSDictionary *attachDic in _attachArray) {
            AttachType attachType = [[attachDic objectForKey:@"type"] intValue];
            if (attachType != FILE_TYPE) {
                continue;
            }
            NSString *filePath = [attachDic objectForKey:@"fileUrl"];
            if ([info.filePath isEqualToString:filePath]) {
                isFound = YES;
                break;
            }
        }
        
        if (isFound) {
            continue;
        }
        NSString *imageName = [AttachTableViewCell getImageWithFileName:info.fileName];
        
        NSError *error;
        NSDictionary* dictFile = [[NSFileManager defaultManager] attributesOfItemAtPath:info.filePath error:&error];
        long size = [dictFile fileSize];
        
        NSDictionary *fileDic = @{@"type": [[NSNumber alloc] initWithInt:FILE_TYPE],
                                   @"title": info.fileName,
                                   @"image": imageName,
                                   @"size": [self addUnitForSize:size withDecimal:2],
                                   @"fileUrl": info.filePath
                                   };//@"size": data
        [shouldAddArray addObject:fileDic];
    }
    [_attachArray addObjectsFromArray:shouldAddArray];
    [_attachView reloadItemData];
    [_parentCtrl attachNumberChanged:_attachArray.count];
}

- (void)removeSandboxItem:(int)index {
    NSDictionary *attachDic = [_attachArray objectAtIndex:index];
    AttachType attachType = [[attachDic objectForKey:@"type"] intValue];
    NSString *filePath = [attachDic objectForKey:@"fileUrl"];
    if (attachType == FILE_TYPE) {
        int selectIndexInt = -1;
        for (NSString *selectIndex in _selectedSandboxIndexs) {
            AttachInfo *info = [_sandboxAttachArray objectAtIndex:[selectIndex intValue]];
            if ([info.filePath isEqualToString:filePath]) {
                selectIndexInt = [selectIndex intValue];
                break;
            }
        }
        if (selectIndexInt != -1) {
            [_selectedSandboxIndexs removeObject:[NSString stringInt:selectIndexInt]];
        }
    }
}

- (void)removeSelectPhoto:(int)selectedPhotoIndex {
    NSDictionary *photoDic = [_attachArray objectAtIndex:selectedPhotoIndex];
    NSDictionary *selectDic = [photoDic valueForKey:@"selectDic"];
    [selectPhotoArray removeObject:selectDic];
}

- (void)removeSelectVideo:(int)selectedVideoIndex {
    NSDictionary *videoDic = [_attachArray objectAtIndex:selectedVideoIndex];
    NSDictionary *selectDic = [videoDic valueForKey:@"selectDic"];
    [selectVideoArray removeObject:selectDic];
}

#pragma mark - QBImagePickerControllerDelegate

- (void)qbimagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(id)info
{
    if(imagePickerController.allowsMultipleSelection) {
        NSArray *mediaInfoArray = (NSArray *)info;
        NSLog(@"Selected %d photos and mediaInfoArray==%@", mediaInfoArray.count,mediaInfoArray);
        NSLog(@"%@", [[mediaInfoArray lastObject] valueForKey:@"UIImagePickerControllerReferenceURL"]);
//        UIImageView *IMAGE = [[UIImageView alloc] initWithImage:[[mediaInfoArray lastObject] objectForKey:@"UIImagePickerControllerOriginalImage"]];
//        IMAGE.size = CGSizeMake(100, 100);
//        [self addSubview:IMAGE];
        
        if (imagePickerController.filterType == QBImagePickerFilterTypeAllPhotos) {
            if (selectPhotoArray == nil) {
                selectPhotoArray = [[NSMutableArray alloc] init];
            }

            [selectPhotoArray removeAllObjects];
            for (NSDictionary *dic in mediaInfoArray) {
                if ([dic objectForKey:@"selectDic"]) {
                    [selectPhotoArray addObject:[dic objectForKey:@"selectDic"]];
                }
            }
            
            NSMutableArray *shouldAddMediaArray = [self checkAttachArrayAndSelectImagesRelationship:mediaInfoArray withAttachType:PHOTO_TYPE];
            
            for (NSDictionary *dic in shouldAddMediaArray) {
                if ([[dic objectForKey:@"UIImagePickerControllerMediaType"] isEqualToString:@"ALAssetTypePhoto"]) {
                    UIImage * image = [dic objectForKey:@"UIImagePickerControllerOriginalImage"];
                    NSArray *array = @[image, @"0"];
                    NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:array];
                    [mutableArray addObject:[dic objectForKey:@"UIImagePickerControllerReferenceURL"]];
                    if ([dic objectForKey:@"selectDic"]) {
                        [mutableArray addObject:[dic objectForKey:@"selectDic"]];
                    }
                    [self performSelector:@selector(saveImage:) withObject:mutableArray afterDelay:0.5];
                }
            }
            
        } else if (imagePickerController.filterType == QBImagePickerFilterTypeAllVideos) {
            if (selectVideoArray == nil) {
                selectVideoArray = [[NSMutableArray alloc] init];
            }
            
            [selectVideoArray removeAllObjects];
            for (NSDictionary *dic in mediaInfoArray) {
                if ([dic objectForKey:@"selectDic"]) {
                    [selectVideoArray addObject:[dic objectForKey:@"selectDic"]];
                }
            }
            NSMutableArray *shouldAddMediaArray = [self checkAttachArrayAndSelectImagesRelationship:mediaInfoArray withAttachType:VIDEO_TYPE];
            for (NSDictionary *dic in shouldAddMediaArray) {
                if ([[dic objectForKey:@"UIImagePickerControllerMediaType"] isEqualToString:@"ALAssetTypeVideo"]) {
                    NSMutableDictionary *infoDic = [NSMutableDictionary dictionaryWithDictionary:dic];
                    [infoDic setValue:@"0" forKey:@"isCamera"];
                    [self saveVideo:infoDic];
                    
                    
//                    NSArray *array = @[image, @"0"];
//                    NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:array];
//                    [mutableArray addObject:[dic objectForKey:@"UIImagePickerControllerReferenceURL"]];
//                    if ([dic objectForKey:@"selectDic"]) {
//                        [mutableArray addObject:[dic objectForKey:@"selectDic"]];
//                    }
//                    [self performSelector:@selector(saveImage:) withObject:mutableArray afterDelay:0.5];
                }
            }
        }
    }

    [_parentCtrl dismissViewControllerAnimated:YES completion:NULL];
}


- (NSMutableArray *)checkAttachArrayAndSelectImagesRelationship:(NSArray *)mediaInfoArray withAttachType:(AttachType)_attachType {

    NSMutableArray *shouldDeleteArray = [[NSMutableArray alloc] initWithCapacity:_attachArray.count];
    
    for (NSDictionary *attachDic in _attachArray) {
        AttachType attachType = [[attachDic objectForKey:@"type"] intValue];
        if (attachType != _attachType) {
            continue;
        }
        if ([[attachDic objectForKey:@"isCamera"] isEqualToString:@"1"]) {
            continue;
        }

        NSString *attachFileUrl = [attachDic objectForKey:@"fileUrl"];
        
        BOOL isFound = NO;
        for (NSDictionary *selectMedia in mediaInfoArray) {
            NSString *mediaFileUrl;

            id obj = [selectMedia objectForKey:@"UIImagePickerControllerReferenceURL"];
            if ([obj isKindOfClass:[NSString class]]) {
                mediaFileUrl = obj;
            } else if ([obj isKindOfClass:[NSURL class]]) {
                mediaFileUrl = [((NSURL *)obj) absoluteString];
            }
            if ([attachFileUrl isEqualToString:mediaFileUrl]) {
                isFound = YES;
                break;
            }
        }
        
        //edit by 王志刚 at 2014-12-13 22:06 isFound == NO修改成 isFound != NO，解决
        //公务邮件-新邮件，添加附件时，如添加照片，若第一次添加的照片在文件夹1下，第二次再添加文件夹2中的照片，则文件夹1中的照片会消失，仅显示文件夹2中的照片。
        if (isFound != NO) {
            [shouldDeleteArray addObject:attachDic];
        }
        //end edit by 王志刚 at 2014-12-13 22:06
    }
    
    [_attachArray removeObjectsInArray:shouldDeleteArray];
    
    NSMutableArray *shouldAddArray = [[NSMutableArray alloc] initWithCapacity:mediaInfoArray.count];
    
    for (NSDictionary *selectMedia in mediaInfoArray) {
        NSString *mediaFileUrl;
        id obj = [selectMedia objectForKey:@"UIImagePickerControllerReferenceURL"];
        if ([obj isKindOfClass:[NSString class]]) {
            mediaFileUrl = obj;
        } else if ([obj isKindOfClass:[NSURL class]]) {
            mediaFileUrl = [((NSURL *)obj) absoluteString];
        }
        BOOL isFound = NO;
        for (NSDictionary *attachDic in _attachArray) {
            AttachType attachType = [[attachDic objectForKey:@"type"] intValue];
            if (attachType != _attachType) {
                continue;
            }
            if ([[attachDic objectForKey:@"isCamera"] isEqualToString:@"1"]) {
                continue;
            }

            NSString *attachFileUrl = [attachDic objectForKey:@"fileUrl"];
            if ([attachFileUrl isEqualToString:mediaFileUrl]) {
                isFound = YES;
                break;
            }
        }
        
        if (isFound) {
            continue;
        }
        [shouldAddArray addObject:selectMedia];
    }
    return shouldAddArray;
}

- (void)qbimagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    NSLog(@"取消选择");
    
    [_parentCtrl dismissViewControllerAnimated:YES completion:NULL];
}

- (NSString *)descriptionForSelectingAllAssets:(QBImagePickerController *)imagePickerController
{
    return @"";
}

- (NSString *)descriptionForDeselectingAllAssets:(QBImagePickerController *)imagePickerController
{
    return @"";
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfPhotos:(NSUInteger)numberOfPhotos
{
    return [NSString stringWithFormat:@"图片%d张", numberOfPhotos];
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfVideos:(NSUInteger)numberOfVideos
{
    return [NSString stringWithFormat:@"视频%d", numberOfVideos];
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfPhotos:(NSUInteger)numberOfPhotos numberOfVideos:(NSUInteger)numberOfVideos
{
    return [NSString stringWithFormat:@"图片%d 视频%d", numberOfPhotos, numberOfVideos];
}

- (void)reloadAttachView {
    [_attachView reloadItemData];
    [_parentCtrl attachNumberChanged:_attachArray.count];
}

@end
